package com.example.usermanagement.liuka.controller;


import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.usermanagement.exception.ObjectNotException;
import com.example.usermanagement.liuka.model.SysUser;
import com.example.usermanagement.liuka.service.SysUserService;
import com.example.usermanagement.schel.RandomFlowService;
import com.example.usermanagement.vo.UserInfoVO;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.util.Objects;


/**
 * 测试接口
 */
@RestController
@RequestMapping("/test")
public class testController {


    private RandomFlowService randomFlowService;

    private SysUserService userService;


    @Autowired
    public testController(RandomFlowService randomFlowService,SysUserService userService){
        this.randomFlowService = randomFlowService;
        this.userService = userService;
    }


    /**
     * 系统用户登录
     * @param username
     * @param password
     * @return
    **/
    @PostMapping("/login")
    public JSONObject login(@NotBlank(message = "username不能为空")String username,
                            @NotBlank(message = "password不能为空")String password) throws ObjectNotException, UnsupportedEncodingException {
        SysUser user = userService.getOne(Wrappers.lambdaQuery(new SysUser())
                .eq(SysUser::getUsername,username)
                .eq(SysUser::getPassword,password));
        if(Objects.isNull(user)){
            throw new ObjectNotException("账号错误");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setName(user.getName());
        userInfoVO.setUserId(user.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", Base64.encode(JSONObject.toJSONString(userInfoVO).getBytes("UTF-8")));
        return jsonObject;
    }

    /**
     * 使用流量上报
     */
    @GetMapping()
    public void  test(){
        this.randomFlowService.schelFlow();
    }


}
